


<!DOCTYPE html>
<html lang="zh-CN">
  <head><meta name="generator" content="Hexo 3.8.0">
    <title>添加实例属性 — Vue.js</title>
    <meta charset="utf-8">
    <meta name="description" content="Vue.js - The Progressive JavaScript Framework">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="alternate" hreflang="x-default" href="https://vuejs.org/v2/cookbook/adding-instance-properties.html">
    <link rel="alternate" hreflang="zh" href="adding-instance-properties.html">
    <link rel="alternate" hreflang="ja" href="https://jp.vuejs.org/v2/cookbook/adding-instance-properties.html">
    <link rel="alternate" hreflang="ru" href="https://ru.vuejs.org/v2/cookbook/adding-instance-properties.html">
    <link rel="alternate" hreflang="ko" href="https://kr.vuejs.org/v2/cookbook/adding-instance-properties.html">
    <link rel="alternate" hreflang="pt-BR" href="https://br.vuejs.org/v2/cookbook/adding-instance-properties.html">
    <link rel="alternate" hreflang="fr" href="https://fr.vuejs.org/v2/cookbook/adding-instance-properties.html">

    <meta property="og:type" content="article">
    <meta property="og:title" content="添加实例属性 — Vue.js">
    <meta property="og:description" content="Vue.js - The Progressive JavaScript Framework">
    <meta property="og:image" content="https://cn.vuejs.org//images/logo.png">

    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="添加实例属性 — Vue.js">
    <meta name="twitter:description" content="Vue.js - The Progressive JavaScript Framework">
    <meta name="twitter:image" content="https://cn.vuejs.org/images/logo.png">

    <link rel="apple-touch-icon" sizes="57x57" href="../../images/icons/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="../../images/icons/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="../../images/icons/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="../../images/icons/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="../../images/icons/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="../../images/icons/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="../../images/icons/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="../../images/icons/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="../../images/icons/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192" href="../../images/icons/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="../../images/icons/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="../../images/icons/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="../../images/icons/favicon-16x16.png">
    <meta name="msapplication-TileImage" content="/images/icons/ms-icon-144x144.png">
    <link rel="icon" href="../../images/logo.png" type="image/png">

    <meta name="msapplication-TileColor" content="#4fc08d">
    <meta name="theme-color" content="#4fc08d">

    <meta name="msapplication-config" content="browserconfig.xml">
    <link rel="manifest" href="../../manifest.json">

    <!-- <link href="https://fonts.googleapis.com" rel="preconnect" crossorigin> -->
    <!-- <link href="https://fonts.gstatic.com" rel="preconnect" crossorigin> -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com" rel="preconnect" crossorigin> -->

    <!-- <link href='//fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600|Roboto Mono' rel='stylesheet' type='text/css'> -->
    <!-- <link href='//fonts.googleapis.com/css?family=Dosis:500&text=Vue.js' rel='stylesheet' type='text/css'> -->

    <link href="https://code.bdstatic.com/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <!-- main page styles -->
    <link rel="stylesheet" href="../../css/page.css">

    <!-- this needs to be loaded before guide's inline scripts -->
    <script src="../../js/vue.js"></script>

    

    <script>
      Vue.config.productionTip = false
      window.PAGE_TYPE = "cookbook"
    </script>

    <!-- ga -->
    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

      ga('create', 'UA-46852172-3', 'cn.vuejs.org');
      ga('send', 'pageview');
    </script>
  </head>
  <body class="docs">
    <div id="mobile-bar">
      <a class="menu-button"></a>
      <a class="logo" href="../../index.html"></a>
    </div>
    <div id="header">
  <a id="logo" href="../../index.html">
    <img src="../../images/logo.png" alt="vue logo">
    <span>Vue.js</span>
  </a>
  <ul id="nav">
    <li>
  <form id="search-form">
    <input type="text" id="search-query-nav" class="search-query st-default-search-input" aria-label="搜索">
  </form>
</li>
<li class="nav-dropdown-container learn">
  <a class="nav-link current">学习</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><h4>文档</h4></li>
    <li>
      <ul>
        <li><a href="../guide/index.html" class="nav-link">教程</a></li>
        <li><a href="../api/index.html" class="nav-link">API</a></li>
        <li><a href="../style-guide/index.html" class="nav-link">风格指南</a></li>
        <li><a href="../examples/index.html" class="nav-link">示例</a></li>
        <li><a href="index.html" class="nav-link current">Cookbook</a></li>
      </ul>
    </li>
    <li><h4>视频教程</h4></li>
    <li>
      <ul>
        <li><a href="https://www.vuemastery.com/courses/" class="nav-link" target="_blank" rel="sponsored noopener">Vue Mastery (英文)</a></li>
        <li><a href="https://vueschool.io/?friend=vuejs&amp;utm_source=Vuejs.org&amp;utm_medium=Link&amp;utm_content=Navbar%20Dropdown" class="nav-link" target="_blank" rel="noopener">Vue School (英文)</a></li>
        <li><a href="https://learning.dcloud.io/" class="nav-link" target="_blank" rel="sponsored noopener">DCloud 视频教程</a></li>
      </ul>
    </li>
  </ul>
</li>

<li class="nav-dropdown-container ecosystem">
  <a class="nav-link">生态系统</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><h4>帮助</h4></li>
    <li><ul>
      <li><a href="https://forum.vuejs.org/" class="nav-link" target="_blank" rel="noopener">论坛</a></li>
      <li><a href="https://chat.vuejs.org/" class="nav-link" target="_blank" rel="noopener">聊天室</a></li>
      <li><a href="https://events.vuejs.org/meetups/" class="nav-link" target="_blank" rel="noopener">聚会</a></li>
    </ul></li>
    <li><h4>工具</h4></li>
    <li>
      <ul>
        <li><a href="https://github.com/vuejs/vue-devtools" class="nav-link" target="_blank" rel="noopener">Devtools</a></li>
        <li><a href="https://cli.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue CLI</a></li>
        <li><a href="https://vue-loader.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue Loader</a></li>
      </ul>
    </li>
    <li><h4>核心插件</h4></li>
    <li><ul>
      <li><a href="https://router.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue Router</a></li>
      <li><a href="https://vuex.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vuex</a></li>
      <li><a href="https://ssr.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue 服务端渲染</a></li>
    </ul></li>
    <li><h4>信息</h4></li>
    <li><ul>
      <li><a href="https://news.vuejs.org" class="nav-link" target="_blank" rel="noopener">周刊</a></li>
      <li><a href="https://github.com/vuejs/vue/projects/6" class="nav-link" target="_blank" rel="noopener">Roadmap</a></li>
      <li><a href="https://events.vuejs.org/" class="nav-link" target="_blank" rel="noopener">活动</a></li>
      <li><a href="https://twitter.com/vuejs" class="nav-link" target="_blank" rel="noopener">Twitter</a></li>
      <li><a href="https://medium.com/the-vue-point" class="nav-link" target="_blank" rel="noopener">博客</a></li>
      <li><a href="https://vuejobs.com/?ref=vuejs" class="nav-link" target="_blank" rel="noopener">工作</a></li>
    </ul></li>
  </ul>
</li>

<li>
  <a href="../guide/team.html" class="nav-link team">团队</a>
</li>
<li class="nav-dropdown-container resources">
  <a href="#" class="nav-link">资源列表</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="../../resources/partners.html" class="nav-link">合作伙伴</a></li>
    <li><a href="../../resources/themes.html" class="nav-link">主题</a></li>
    <li><a href="https://github.com/vuejs/awesome-vue" class="nav-link" target="_blank">Awesome Vue</a></li>
  </ul>
</li>

<!-- <li>
  <a href="/partners" class="nav-link ">Partners</a>
</li> -->
<li class="nav-dropdown-container support-vue">
  <a href="../../support-vuejs/index.html" class="nav-link">支持 Vue</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="../../support-vuejs/index.html#One-time-Donations" class="nav-link">一次性赞助</a></li>
    <li><a href="../../support-vuejs/index.html#Recurring-Pledges" class="nav-link">周期性赞助</a></li>
    <li><a href="https://www.smallsticker.com/%E8%B4%B4%E7%BA%B8/vue.html" rel="noopener" class="nav-link">贴纸</a></li>
    <li><a href="https://osholic.com/?utm_source=vue&amp;utm_medium=dropdown" rel="noopener" class="nav-link">周边</a></li>
    <li><a href="https://vue.threadless.com" target="_blank" rel="noopener" class="nav-link">T 恤商店</a></li>
  </ul>
</li>

<li class="nav-dropdown-container language">
  <a class="nav-link">多语言</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="https://vuejs.org/v2/cookbook/adding-instance-properties.html" class="nav-link" target="_blank" rel="noopener">English</a></li>
    <li><a href="https://jp.vuejs.org/v2/cookbook/adding-instance-properties.html" class="nav-link" target="_blank" rel="noopener">日本語</a></li>
    <li><a href="https://ru.vuejs.org/v2/cookbook/adding-instance-properties.html" class="nav-link" target="_blank" rel="noopener">Русский</a></li>
    <li><a href="https://kr.vuejs.org/v2/cookbook/adding-instance-properties.html" class="nav-link" target="_blank" rel="noopener">한국어</a></li>
    <li><a href="https://br.vuejs.org/v2/cookbook/adding-instance-properties.html" class="nav-link" target="_blank" rel="noopener">Português</a></li>
    <li><a href="https://fr.vuejs.org/v2/cookbook/adding-instance-properties.html" class="nav-link" target="_blank" rel="noopener">Français</a></li>
    <li><a href="https://vi.vuejs.org/v2/cookbook/adding-instance-properties.html" class="nav-link" target="_blank" rel="noopener">Tiếng Việt</a></li>
  </ul>
</li>

<li><a href="https://github.com/vuejs/cn.vuejs.org/" target="_blank" class="nav-link contribute">参与翻译</a></li>

  </ul>
</div>

    
      <div id="main" class="fix-sidebar">
        
          
  

<div class="sidebar">
  <div class="sidebar-inner">
    
    <div class="list">
      <div id="sidebar-sponsors-special">
  <div class="main-sponsor">
    <span>特别赞助商</span>
    <div>
    <a href="http://www.dcloud.io/?hmsr=vuejsorg&amp;hmpl=&amp;hmcu=&amp;hmkw=&amp;hmci=" target="_blank" rel="sponsored noopener" class="logo">
      <img src="../../images/dcloud.gif" alt="">
    </a>
    </div>
    <div>
    <a href="https://youzan.github.io/vant?source=vuejsorg" target="_blank" rel="sponsored noopener" class="logo">
      <img src="../../images/vant.png" alt="">
    </a>
    </div>
  </div>
</div>
<!--

<div id="sidebar-sponsors-platinum-left">
  <div class="main-sponsor">
    <span>白金赞助商</span>
    <div>
    <a href="https://vueschool.io/?utm_source=Vuejs.org&utm_medium=Banner&utm_campaign=Sponsored%20Banner&utm_content=V1" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vueschool.png" alt="VueSchool">
    </a>
    <a href="https://vehikl.com/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vehikl.png" alt="Vehikl">
    </a>
    <a href="https://www.nativescript.org/vue?utm_source=vue-js-org&utm_medium=website&utm_campaign=nativescript-awareness" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/nativescript.png" alt="NativeScript">
    </a>
    <a href="https://retool.com/?utm_source=sponsor&utm_campaign=vue" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/retool.png" alt="Retool">
    </a>
    </div>
  </div>
  <a class="become-backer" href="/support-vuejs">
    成为赞助者
  </a>
</div>


-->

      
        <h2>
          
          Cookbook<sup class="beta">beta</sup>
          
        </h2>
        <ul class="menu-root">
  
    
    
    <li>
      <a href="index.html" class="sidebar-link">介绍</a>
    </li>
  
    
    
    <li>
      <a href="adding-instance-properties.html" class="sidebar-link current">添加实例属性</a>
    </li>
  
    
    
    <li>
      <a href="form-validation.html" class="sidebar-link">表单校验</a>
    </li>
  
    
    
    <li>
      <a href="editable-svg-icons.html" class="sidebar-link">可编辑的 SVG 图标系统</a>
    </li>
  
    
    
    <li>
      <a href="serverless-blog.html" class="sidebar-link">创建一个基于 CMS 的博客</a>
    </li>
  
    
    
    <li>
      <a href="unit-testing-vue-components.html" class="sidebar-link">Vue 组件的单元测试</a>
    </li>
  
    
    
    <li>
      <a href="creating-custom-scroll-directives.html" class="sidebar-link">创建自定义滚动指令</a>
    </li>
  
    
    
    <li>
      <a href="debugging-in-vscode.html" class="sidebar-link">在 VS Code 中调试</a>
    </li>
  
    
    
    <li>
      <a href="using-axios-to-consume-apis.html" class="sidebar-link">使用 axios 访问 API</a>
    </li>
  
    
    
    <li>
      <a href="avoiding-memory-leaks.html" class="sidebar-link">避免内存泄漏</a>
    </li>
  
    
    
    <li>
      <a href="client-side-storage.html" class="sidebar-link">客户端存储</a>
    </li>
  
    
    
    <li>
      <a href="packaging-sfc-for-npm.html" class="sidebar-link">Packaging Vue Components for npm</a>
    </li>
  
    
    
    <li>
      <a href="dockerize-vuejs-app.html" class="sidebar-link">Dockerize Vue.js App</a>
    </li>
  
    
    
    <li>
      <a href="practical-use-of-scoped-slots.html" class="sidebar-link">Practical use of scoped slots with GoogleMaps</a>
    </li>
  
</ul>

      
    </div>
  </div>
</div>
<!--

<div id="sidebar-sponsors-platinum-right">
  <div class="main-sponsor">
    <span>白金赞助商</span>
    <div>
    <a href="https://vueschool.io/?utm_source=Vuejs.org&utm_medium=Banner&utm_campaign=Sponsored%20Banner&utm_content=V1" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vueschool.png" alt="VueSchool">
    </a>
    <a href="https://vehikl.com/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vehikl.png" alt="Vehikl">
    </a>
    <a href="https://www.nativescript.org/vue?utm_source=vue-js-org&utm_medium=website&utm_campaign=nativescript-awareness" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/nativescript.png" alt="NativeScript">
    </a>
    <a href="https://retool.com/?utm_source=sponsor&utm_campaign=vue" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/retool.png" alt="Retool">
    </a>
    </div>
  </div>
  <a class="become-backer" href="/support-vuejs">
    成为赞助者
  </a>
</div>


-->


<div class="content cookbook with-sidebar ">
  
    
      
<div id="ad">
  <span style="float: right;">广告</span>
  <a href="https://time.geekbang.org/column/intro/216?code=mM%2FdqOPks0VQ7EkYGPNisoEpHDsb0ViHBXYa%2Fyg02k8%3D&amp;utm_term=SPoster" target="_blank" rel="sponsored noopener">
    <img src="../../images/geekbang-ad.jpg">
  </a>
  <!-- <a href="https://ke.qq.com/course/392130?saleToken=992600&from=pclink" target="_blank" rel="sponsored noopener">
    <img src="/images/tencent-ad.png">
  </a> -->
  <!-- <script
    async
    type="text/javascript"
    src="//cdn.carbonads.com/carbon.js?serve=CKYIK2QU&placement=vuejsorg"
    id="_carbonads_js">
  </script> -->
</div>


    
  
  
    <h1>添加实例属性</h1>
  

  <div class="ad-pagetop">
  <a href="http://www.tp-shop.cn/index.php?http_referer=vuejs" target="_blank" rel="noopener noreferrer">
    <span class="name">TPshop</span>
    <span class="description">中国免费商城系统 - 搜豹商城系统 - 免费50小时Vue视频教程</span>
    <span class="action">立即查看 &gt;</span>
  </a>
</div>


  
    <h2 id="基本的示例"><a href="#%E5%9F%BA%E6%9C%AC%E7%9A%84%E7%A4%BA%E4%BE%8B" class="headerlink" title="基本的示例"></a>基本的示例</h2><p>你可能会在很多组件里用到数据/实用工具，但是不想<a href="https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md" target="_blank" rel="noopener">污染全局作用域</a>。这种情况下，你可以通过在原型上定义它们使其在每个 Vue 的实例中可用。</p>
<pre><code class="hljs js">Vue.prototype.$appName = <span class="hljs-string">'My App'</span></code></pre>
<p>这样 <code>$appName</code> 就在所有的 Vue 实例中可用了，甚至在实例被创建之前就可以。如果我们运行：</p>
<pre><code class="hljs js"><span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">beforeCreate</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">this</span>.$appName)
  &#125;
&#125;)</code></pre>
<p>则控制台会打印出 <code>My App</code>。就这么简单！</p>
<h2 id="为实例属性设置作用域的重要性"><a href="#%E4%B8%BA%E5%AE%9E%E4%BE%8B%E5%B1%9E%E6%80%A7%E8%AE%BE%E7%BD%AE%E4%BD%9C%E7%94%A8%E5%9F%9F%E7%9A%84%E9%87%8D%E8%A6%81%E6%80%A7" class="headerlink" title="为实例属性设置作用域的重要性"></a>为实例属性设置作用域的重要性</h2><p>你可能会好奇：</p>
<blockquote>
<p>“为什么 <code>appName</code> 要以 <code>$</code> 开头？这很重要吗？它会怎样？”</p>
</blockquote>
<p>这里没有什么魔法。<code>$</code> 是在 Vue 所有实例中都可用的属性的一个简单约定。这样做会避免和已被定义的数据、方法、计算属性产生冲突。</p>
<blockquote>
<p>“你指的冲突是什么意思？”</p>
</blockquote>
<p>另一个好问题！如果你写成：</p>
<pre><code class="hljs js">Vue.prototype.appName = <span class="hljs-string">'My App'</span></code></pre>
<p>那么你希望下面的代码输出什么呢？</p>
<pre><code class="hljs js"><span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">data</span>: &#123;
    <span class="hljs-comment">// 啊哦，`appName` *也*是一个我们定义的实例属性名！😯</span>
    appName: <span class="hljs-string">'The name of some other app'</span>
  &#125;,
  <span class="hljs-attr">beforeCreate</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">this</span>.appName)
  &#125;,
  <span class="hljs-attr">created</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">this</span>.appName)
  &#125;
&#125;)</code></pre>
<p>日志中会先出现 <code>&quot;My App&quot;</code>，然后出现 <code>&quot;The name of some other app&quot;</code>，因为 <code>this.appName</code> 在实例被创建之后被 <code>data</code> <a href="https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch5.md" target="_blank" rel="noopener">覆写了</a>。我们通过 <code>$</code> 为实例属性设置作用域来避免这种事情发生。你还可以根据你的喜好使用自己的约定，诸如 <code>$_appName</code> 或 <code>ΩappName</code>，来避免和插件或未来的插件相冲突。</p>
<h2 id="真实的示例：通过-axios-替换-Vue-Resource"><a href="#%E7%9C%9F%E5%AE%9E%E7%9A%84%E7%A4%BA%E4%BE%8B%EF%BC%9A%E9%80%9A%E8%BF%87-axios-%E6%9B%BF%E6%8D%A2-Vue-Resource" class="headerlink" title="真实的示例：通过 axios 替换 Vue Resource"></a>真实的示例：通过 axios 替换 Vue Resource</h2><p>比如你打算替换已经废弃的 <a href="https://medium.com/the-vue-point/retiring-vue-resource-871a82880af4" target="_blank" rel="noopener">Vue Resource</a> 库。你实在是很喜欢通过 <code>this.$http</code> 来访问请求方法，希望换成 axios 以后还能继续这样用。</p>
<p>你需要做的事情是把 axios 引入你的项目：</p>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://cdnjs.cloudflare.com/ajax/libs/axios/0.15.2/axios.js"</span>&gt;</span><span class="undefined"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"app"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">v-for</span>=<span class="hljs-string">"user in users"</span>&gt;</span>&#123;&#123; user.name &#125;&#125;<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre>
<p>设置 <code>Vue.prototype.$http</code> 为 <code>axios</code> 的别名：</p>
<pre><code class="hljs js">Vue.prototype.$http = axios</code></pre>
<p>然后你就可以在任何 Vue 实例中使用类似 <code>this.$http.get</code> 的方法：</p>
<pre><code class="hljs js"><span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">el</span>: <span class="hljs-string">'#app'</span>,
  <span class="hljs-attr">data</span>: &#123;
    <span class="hljs-attr">users</span>: []
  &#125;,
  created () &#123;
    <span class="hljs-keyword">var</span> vm = <span class="hljs-keyword">this</span>
    <span class="hljs-keyword">this</span>.$http
      .get(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users'</span>)
      .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">response</span>) </span>&#123;
        vm.users = response.data
      &#125;)
  &#125;
&#125;)</code></pre>
<h2 id="原型方法的上下文"><a href="#%E5%8E%9F%E5%9E%8B%E6%96%B9%E6%B3%95%E7%9A%84%E4%B8%8A%E4%B8%8B%E6%96%87" class="headerlink" title="原型方法的上下文"></a>原型方法的上下文</h2><p>你可能没有意识到，在 JavaScript 中一个原型的方法会获得该实例的上下文。也就是说它们可以使用 <code>this</code> 访问数据、计算属性、方法或其它任何定义在实例上的东西。</p>
<p>让我们将其用在一个名为 <code>$reverseText</code> 的方法上：</p>
<pre><code class="hljs js">Vue.prototype.$reverseText = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">propertyName</span>) </span>&#123;
  <span class="hljs-keyword">this</span>[propertyName] = <span class="hljs-keyword">this</span>[propertyName]
    .split(<span class="hljs-string">''</span>)
    .reverse()
    .join(<span class="hljs-string">''</span>)
&#125;

<span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">data</span>: &#123;
    <span class="hljs-attr">message</span>: <span class="hljs-string">'Hello'</span>
  &#125;,
  <span class="hljs-attr">created</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">this</span>.message) <span class="hljs-comment">// =&gt; "Hello"</span>
    <span class="hljs-keyword">this</span>.$reverseText(<span class="hljs-string">'message'</span>)
    <span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">this</span>.message) <span class="hljs-comment">// =&gt; "olleH"</span>
  &#125;
&#125;)</code></pre>
<p>注意如果你使用了 ES6/2015 的箭头函数，则其绑定的上下文<strong>不会</strong>正常工作，因为它们会隐式地绑定其父级作用域。也就是说使用箭头函数的版本：</p>
<pre><code class="hljs js">Vue.prototype.$reverseText = <span class="hljs-function"><span class="hljs-params">propertyName</span> =&gt;</span> &#123;
  <span class="hljs-keyword">this</span>[propertyName] = <span class="hljs-keyword">this</span>[propertyName]
    .split(<span class="hljs-string">''</span>)
    .reverse()
    .join(<span class="hljs-string">''</span>)
&#125;</code></pre>
<p>会抛出一个错误：</p>
<pre><code class="hljs log">Uncaught TypeError: Cannot read property &apos;split&apos; of undefined</code></pre>
<h2 id="何时避免使用这个模式"><a href="#%E4%BD%95%E6%97%B6%E9%81%BF%E5%85%8D%E4%BD%BF%E7%94%A8%E8%BF%99%E4%B8%AA%E6%A8%A1%E5%BC%8F" class="headerlink" title="何时避免使用这个模式"></a>何时避免使用这个模式</h2><p>只要你对原型属性的作用域保持警惕，那么使用这个模式就是安全的——保证了这一点，就不太会出 bug。</p>
<p>然而，有的时候它会让其他开发者感到混乱。例如他们可能看到了 <code>this.$http</code>，然后会想“哦，我从来没见过这个 Vue 的功能”，然后他们来到另外一个项目又发现 <code>this.$http</code> 是未被定义的。或者你打算去搜索如何使用它，但是搜不到结果，因为他们并没有发现这是一个 axios 的别名。</p>
<p><strong>这种便利是以显性表达为代价的。</strong>当我们查阅一个组件的时候，要注意交代清楚 <code>$http</code> 是从哪来的：Vue 自身、一个插件、还是一个辅助库？</p>
<p>那么有别的替代方案吗？</p>
<h2 id="替代方案"><a href="#%E6%9B%BF%E4%BB%A3%E6%96%B9%E6%A1%88" class="headerlink" title="替代方案"></a>替代方案</h2><h3 id="当没有使用模块系统时"><a href="#%E5%BD%93%E6%B2%A1%E6%9C%89%E4%BD%BF%E7%94%A8%E6%A8%A1%E5%9D%97%E7%B3%BB%E7%BB%9F%E6%97%B6" class="headerlink" title="当没有使用模块系统时"></a>当没有使用模块系统时</h3><p>在<strong>没有</strong>模块系统 (比如 webpack 或 Browserify) 的应用中，存在一种<em>任何</em>重 JS 前端应用都常用的模式：一个全局的 <code>App</code> 对象。</p>
<p>如果你想要添加的东西跟 Vue 本身没有太多关系，那么这是一个不错的替代方案。举个例子：</p>
<pre><code class="hljs js"><span class="hljs-keyword">var</span> App = <span class="hljs-built_in">Object</span>.freeze(&#123;
  <span class="hljs-attr">name</span>: <span class="hljs-string">'My App'</span>,
  <span class="hljs-attr">version</span>: <span class="hljs-string">'2.1.4'</span>,
  <span class="hljs-attr">helpers</span>: &#123;
    <span class="hljs-comment">// 这是我们之前见到过的 `$reverseText` 方法</span>
    <span class="hljs-comment">// 的一个纯函数版本</span>
    reverseText: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">text</span>) </span>&#123;
      <span class="hljs-keyword">return</span> text
        .split(<span class="hljs-string">''</span>)
        .reverse()
        .join(<span class="hljs-string">''</span>)
    &#125;
  &#125;
&#125;)</code></pre>
<p class="tip">如果你在好奇 <code>Object.freeze</code>，它做的事情是阻止这个对象在未来被修改。这实质上是将它的属性都设为了常量，避免在未来出现状态的 bug。</p>

<p>现在这些被共享的属性的来源就更加明显了：在应用中的某个地方有一个被定义好的 <code>App</code> 对象。你只需在项目中搜索就可以找到它。</p>
<p>这样做的另一个好处是 <code>App</code> 可以在你代码的<em>任何地方</em>使用，不管它是否是 Vue 相关的。包括向实例选项直接附加一些值而不必进入一个函数去访问 <code>this</code> 上的属性来得到这些值：</p>
<pre><code class="hljs js"><span class="hljs-keyword">new</span> Vue(&#123;
  <span class="hljs-attr">data</span>: &#123;
    <span class="hljs-attr">appVersion</span>: App.version
  &#125;,
  <span class="hljs-attr">methods</span>: &#123;
    <span class="hljs-attr">reverseText</span>: App.helpers.reverseText
  &#125;
&#125;)</code></pre>
<h3 id="当使用模块系统时"><a href="#%E5%BD%93%E4%BD%BF%E7%94%A8%E6%A8%A1%E5%9D%97%E7%B3%BB%E7%BB%9F%E6%97%B6" class="headerlink" title="当使用模块系统时"></a>当使用模块系统时</h3><p>当使用模块系统的时候，你可以轻松地把共享的代码组织成模块，然后把那些模块 <code>require</code>/<code>import</code> 到任何你所需要的地方。这是一个典型的显式做法，因为在每个文件里你都能得到一份依赖清单。你可以<em>准确地</em>知道每个依赖的来历。</p>
<p>虽然毫无疑问它更啰嗦，但是这种方法确实是最可维护的，尤其是当和多人一起协作一个大型应用的时候。</p>

  
  
  <div class="footer">
      <script src="https://m.servedby-buysellads.com/monetization.js" type="text/javascript"></script>
<div id="bsa-native"></div>
<script>
_bsa.init('custom', 'CKYD62QM', 'placement:vuejsorg',
  {
    target: '#bsa-native',
    template: '<a class="native-box" href="##statlink##"><div class="native-sponsor">Sponsor</div><div class="native-text"><strong>##company##</strong> — ##description##</div></a>'
  }
);
</script>


    发现错误？想参与编辑？
    <a href="https://github.com/vuejs/cn.vuejs.org/blob/master/src/v2/cookbook/adding-instance-properties.md" rel="noopener" target="_blank">
      在 GitHub 上编辑此页！
    </a>
  </div>
</div>

        
      </div>
      <script src="../../js/smooth-scroll.min.js"></script>
    

    <!-- main custom script for sidebars, version selects etc. -->
    <script src="../../js/css.escape.js"></script>
    <script src="../../js/common.js"></script>

    <!-- search -->
    <link href="https://code.bdstatic.com/npm/docsearch.js@1.5.0/dist/cdn/docsearch.min.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="../../css/search.css">
    <script src="https://code.bdstatic.com/npm/docsearch.js@1.5.0/dist/cdn/docsearch.min.js"></script>
    <script>
    [
      '#search-query-nav',
      '#search-query-sidebar',
      '#search-query-menu'
    ].forEach(function (selector) {
      if (!document.querySelector(selector)) return
      // search index defaults to v2
      var match = window.location.pathname.match(/^\/(v\d+)/)
      var version = match ? match[1] : 'v2'
      docsearch({
      appId: 'BH4D9OD16A',
      apiKey: '5638280abff9d207417bb03be05f0b25',
      indexName: 'vuejs_cn2',
      inputSelector: selector,
      algoliaOptions: { facetFilters: ["version:" + version] },
      autocompleteOptions: { hint: false, appendTo: 'body'}
      })
    })
    </script>
  </body>
</html>
